package qeb.handheldmedical;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import qeb.handheldmedical.R;
import qeb.handheldmedical.helper.PhoneInfo;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.Phone;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;

/*登录的欢迎界面*/
public class Welcome extends Activity {

	private TextView txtloadmes;
	private Phone phone;
	private String deviceId;
	private static final String TAG = "Welcome";
	public ProgressDialog pBar;
	private Handler handler = new Handler();

	private int newVerCode = 0;
	private String newVerName = "";
	private String UpdateMessage = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		int currentapiVersion = android.os.Build.VERSION.SDK_INT;
		if (currentapiVersion > 13) {
			// TODO Auto-generated method stub
			// 由于安卓2.3版本以上SOAP协议严格要求要另开线程
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectDiskReads().detectDiskWrites().detectNetwork() // or
																			// .detectAll()
																			// for
																			// all
																			// detectable
																			// problems
					.penaltyLog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
					.build());
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏顶部台头
		// getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN
		// ,WindowManager.LayoutParams. FLAG_FULLSCREEN);//
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sys_welcome);
		txtloadmes = (TextView) findViewById(R.id.txtloadmes);
		txtloadmes.setText("正在检查版本号.....");
		PhoneInfo siminfo = new PhoneInfo(Welcome.this);
		//deviceId = siminfo.telephonemanager.getDeviceId().trim();
		// phone = WSHelper.GetPhoneInfo(deviceId);
		try {
			if (getServerVerCode()) {
				int vercode = WSHelper.getVerCode(this);
				if (newVerCode > vercode) {
					doNewVersionUpdate();
				} else {
					notNewVersionShow();
				}
			}
		} catch (Exception e) {
			Log.d(TAG, e.toString());
		}

	}

	// 版本号相等，不需要更新
	private void notNewVersionShow() {
		final Intent intent = new Intent(Welcome.this, Login.class);
		// 系统会为需要启动的activity寻找与当前activity不同的task;
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.putExtra("isApply", "1");
		// intent.putExtra("isApply", phone.Applystate);

		// if (phone.Applystate != null) {
		// intent.putExtra("isApply", phone.Applystate);
		// }
		// 创建一个新的线程来显示欢迎动画，指定时间后结束，跳转至指定界面
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					txtloadmes.setText("正在启动登录中.....");
					Thread.sleep(3000);
					// 获取应用的上下文，生命周期是整个应用，应用结束才会结束
					getApplicationContext().startActivity(intent);
					finish();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
	}

	// 获取服务器版本号
	private boolean getServerVerCode() {
		int nowVerser = WSHelper.getVerCode(this);// 当前版本号

		String verjson = "";
		JSONObject obj = null;

		verjson = WSHelper.getContent(WSHelper.UPDATE_SERVER
				+ WSHelper.UPDATE_VERJSON);
		// 老版本更新
		try {
			JSONArray array = new JSONArray(verjson);
			if (!array.equals(null) && array.length() > 0) {
				obj = array.getJSONObject(0);
				if (!obj.equals(null)) {
					try {
						newVerCode = Integer.parseInt(obj.getString("verCode"));
						newVerName = obj.getString("verName");
						UpdateMessage = "请稍等，正在更新中.....";
					} catch (Exception e) {
						newVerCode = -1;
						newVerName = "";
					}
				}
			}
		} catch (JSONException e1) { // TODO Auto-generated catch block
			e1.printStackTrace();
		}

		// // 新版本更新
		// try {
		// verjson = WSHelper.getContentWebService(WSHelper.UPDATE_SERVER
		// + WSHelper.UPDATE_VERJSON);
		// obj = new JSONObject(verjson);
		// if (!obj.equals(null)) {
		// try {
		// newVerCode = Integer.parseInt(obj.getString("BUILD"));
		// newVerName = obj.getString("VERSION");
		// UpdateMessage = obj.getString("MESSAGE");
		// } catch (Exception e) {
		// newVerCode = -1;
		// newVerName = "";
		// }
		// }
		// } catch (JSONException e) {
		// Log.e(TAG, e.getMessage());
		// return false;
		// }

		return true;
	}

	// 与服务器版本号不想同，需要更新
	private void doNewVersionUpdate() {
		// int verCode = WSHelper.getVerCode(this);
		String verName = WSHelper.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本:");
		sb.append(verName);
		// sb.append(" Code:");
		// sb.append(verCode);
		sb.append(", 发现新版本:");
		sb.append(newVerName);
		// sb.append(" Code:");
		// sb.append(newVerCode);
		sb.append(", 是否更新?\n\n");
		// sb.append("新版本更新内容：\n");
		// sb.append("1.优化患者信息页面。\n");
		// sb.append("2.修复“在院病人”、“出院病人”应网络差而引起的黑屏现象。\n");
		// sb.append("3.新增“病人信息”关闭按钮。\n");
		// sb.append("4.管理员用户新增在线审批功能。\n");
		Dialog dialog = new AlertDialog.Builder(Welcome.this)
				.setTitle("软件更新")
				.setMessage(sb.toString())
				// 设置内容
				.setPositiveButton("更新",// 设置确定按钮
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								pBar = new ProgressDialog(Welcome.this);
								pBar.setTitle("正在下载");
								pBar.setMessage(UpdateMessage);
								pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
								downFile(WSHelper.UPDATE_SERVER
										+ WSHelper.UPDATE_APKNAME);
							}

						})
				.setNegativeButton("暂不更新",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// 点击"取消"按钮之后退出程序
								finish();
							}
						}).create();// 创建
		// 显示对话框
		dialog.show();
	}

	// 下载文件
	void downFile(final String url) {
		pBar.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {

						File file = new File(
								Environment.getExternalStorageDirectory(),
								WSHelper.UPDATE_SAVENAME);
						fileOutputStream = new FileOutputStream(file);

						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}

					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (ClientProtocolException e) {
					Log.e(TAG, e.getMessage());
					e.printStackTrace();
				} catch (IOException e) {
					Log.e(TAG, e.getMessage());
					e.printStackTrace();
				}
			}

		}.start();

	}

	// 下载后更新安装
	void down() {
		handler.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	// 更新安装
	void update() {

		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), WSHelper.UPDATE_SAVENAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}
}
